package com.ljh.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljh.blog.common.exception.BlogException;
import com.ljh.blog.common.utils.BeanTransUtils;
import com.ljh.blog.common.utils.JwtUtils;
import com.ljh.blog.common.utils.SecurityUtils;
import com.ljh.blog.mapper.UserInfoMapper;
import com.ljh.blog.pojo.dataobject.BlogInfo;
import com.ljh.blog.pojo.dataobject.UserInfo;
import com.ljh.blog.pojo.request.UserInfoRequest;
import com.ljh.blog.pojo.response.UserInfoResponse;
import com.ljh.blog.pojo.response.UserLoginResponse;
import com.ljh.blog.service.BlogService;
import com.ljh.blog.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: Themberfue
 * @date: 2025/3/30 20:50
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    BlogService blogService;

    @Override
    public UserLoginResponse login(UserInfoRequest userInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserInfo::getUserName, userInfo.getUserName())
                .eq(UserInfo::getDeleteFlag, 0);
        UserInfo user = userInfoMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BlogException("用户不存在");
        }

        if (!SecurityUtils.verify(userInfo.getPassword(), user.getPassword())) {
            throw new BlogException("密码错误");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUserName());
        return new UserLoginResponse(user.getId(), JwtUtils.genToken(map));
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag, 0)
                .eq(UserInfo::getId, userId);
        return BeanTransUtils.trans(userInfoMapper.selectOne(queryWrapper));
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if (blogInfo == null || blogInfo.getUserId() < 0) {
            throw new BlogException("用户或博客不存在");
        }
        return getUserInfo(blogInfo.getUserId());
    }
}
